import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_module_sale/common/plugin/bean/bean_error_info.dart';
import 'package:dk_flutter_module_sale/common/plugin/bean/bean_handle_cache.dart';
import 'package:dk_flutter_module_sale/common/plugin/bean/bean_ios_path_type.dart';
import 'package:dk_flutter_module_sale/common/plugin/bean/bean_open_custom_media.dart';
import 'package:dk_flutter_module_sale/common/plugin/bean/bean_open_media.dart';
import 'package:dk_flutter_module_sale/common/plugin/bean/bean_preview_pic.dart';
import 'package:dk_flutter_module_sale/common/plugin/bean/bean_preview_video.dart';
import 'package:dk_flutter_module_sale/common/plugin/bean/bean_record_video.dart';
import 'package:dk_flutter_module_sale/common/plugin/bean/bean_save_pic_2_gallery.dart';
import 'package:dk_flutter_module_sale/common/plugin/bean/bean_share.dart';
import 'package:dk_flutter_module_sale/common/plugin/bean/bean_upload_pic.dart';
import 'package:dk_flutter_module_sale/common/plugin/bean/bean_upload_video.dart';
import 'package:dk_flutter_module_sale/common/plugin/bean/bean_user_info.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';

class CommonPlugin {
  factory CommonPlugin() {
    if (_instance == null) {
      const MethodChannel methodChannel =
          MethodChannel('plugins/dk_common_plugin');

      _instance = CommonPlugin.private(methodChannel);
    }
    return _instance;
  }

  @visibleForTesting
  CommonPlugin.private(this._channel);

  static CommonPlugin _instance;

  final MethodChannel _channel;

  ///预览图片
  ///
  /// *参数-参考[PreviewPicBean]
  Future<bool> previewPic({@required PreviewPicBean bean}) async {
    return _channel.invokeMethod<bool>(
        'DKFlutterHandlePreviewPic', json.encode(bean));
  }

  ///打开相机或者相册
  ///
  /// *参数-参考[OpenMediaBean]
  void openMedia({
    @required OpenMediaBean bean,
    HandleResult<List<String>> handleResult,
  }) async {
    List<String> resultList = await _channel.invokeListMethod<String>(
        'DKFlutterHandleOpenMedia', json.encode(bean));
    if (null != handleResult) {
      handleResult(resultList);
    }
  }

  ///保存图片到相册
  ///
  /// *参数-参考[SavePic2GalleryBean]
  Future<bool> savePic2Gallery({@required SavePic2GalleryBean bean}) async {
    return _channel.invokeMethod<bool>(
        'DKFlutterHandleSavePic2Gallery', json.encode(bean));
  }

  ///上传图片
  ///
  /// *参数-参考[UploadPicBean]
  void uploadPic({
    @required UploadPicBean bean,
    HandleResult<List<String>> handleResult,
  }) async {
    List<String> resultList = await _channel.invokeListMethod<String>(
        'DKFlutterHandleUploadPic', json.encode(bean));
    if (null != resultList) {
      handleResult(resultList);
    }
  }

  ///录制视频
  ///
  /// *参数-参考[RecordVideoBean]
  /// *结果-参考[RecordVideoResultBean]
  void recordVideo({
    @required RecordVideoBean bean,
    HandleResult<RecordVideoResultBean> handleResult,
  }) async {
    String result = await _channel.invokeMethod<String>(
        'DKFlutterHandleRecordVideo', json.encode(bean));
    if (stringBlank(result) || null == handleResult) {
      return;
    }
    handleResult(RecordVideoResultBean.fromJson(json.decode(result)));
  }

  ///选取相册视频
  ///
  /// *参数-参考[RecordVideoBean]
  /// *结果-参考[RecordVideoResultBean]
  void selectGalleryVideo({
    @required RecordVideoBean bean,
    HandleResult<RecordVideoResultBean> handleResult,
  }) async {
    String result = await _channel.invokeMethod<String>(
        'DKFlutterHandleGalleryVideo', json.encode(bean));
    if (stringBlank(result) || null == handleResult) {
      return;
    }
    handleResult(RecordVideoResultBean.fromJson(json.decode(result)));
  }

  ///预览视频
  ///
  /// *参数-参考[PreviewVideoBean]
  Future<bool> previewVideo({@required PreviewVideoBean bean}) async {
    return _channel.invokeMethod<bool>(
        'DKFlutterHandlePreviewVideo', json.encode(bean));
  }

  ///上传视频
  ///
  /// *参数-参考[UploadVideoBean]
  void uploadVideo({
    @required UploadVideoBean bean,
    HandleResult<UploadVideoResultBean> handleResult,
  }) async {
    String result = await _channel.invokeMethod<String>(
        'DKFlutterHandleUploadVideo', json.encode(bean));
    if (stringBlank(result) || null == handleResult) {
      return;
    }
    print("--------------------------------" + result);
    handleResult(UploadVideoResultBean.fromJson(json.decode(result)));
  }


  ///分享
  ///
  /// *参数-参考[ShareBean]
  Future<bool> share({@required ShareBean bean}) async {
    return _channel.invokeMethod<bool>(
        'DKFlutterHandleShare', json.encode(bean));
  }

  ///上传错误信息
  ///
  /// *参数-参考[ErrorInfoBean]
  Future<bool> uploadError({@required ErrorInfoBean bean}) async {
    return _channel.invokeMethod<bool>(
        'DKFlutterHandleErrorInfo', json.encode(bean));
  }

  ///打开自定义相机、相册，返回图片路径
  ///
  /// *handleResult 处理返回路径的回调
  /// *参数-参考[OpenCustomMediaBean]
  /// *结果-参考[CustomMediaResultBean]
  void openCustomMedia({
    @required OpenCustomMediaBean bean,
    HandleResult<CustomMediaResultBean> handleResult,
  }) async {
    Map result = await _channel.invokeMapMethod(
        'DKFlutterHandleOpenCustomMedia', json.encode(bean));
    if (mapEmpty(result) || null == handleResult) {
      return;
    }
    handleResult(CustomMediaResultBean(
      listResult: List.from(result.keys),
      mapResult: result,
    ));
  }

  ///Flutter缓存操作
  ///
  /// *异步、单、多、存储、删除、清空数据
  /// *HandleCacheResultBean 根据操作类型返回不同的结果，失败返回null
  /// *参数-参考[CacheOption]
  /// *结果-参考[CacheOptionType]
  void handleCache(
      {@required CacheOption option,
      HandleResult<HandleCacheResultBean> handleResult}) async {
    String result = await _channel.invokeMethod<String>(
        'DKFlutterHandleCache', json.encode(option.toJson()));
    if (null == handleResult) {
      return;
    }
    HandleCacheResultBean resultBean =
        HandleCacheResultBean.fromJson(json.decode(result));
    /*if (Platform.isIOS) {
      if (CacheOptionType.get == option.type &&
          CacheValueType.file == option.valueType) {
        String prefix = await getIosPath();
        //单一类型
        resultBean.getResult = prefix + resultBean.getResult;
      } else if (CacheOptionType.multiGet == option.type &&
          CacheValueType.file == option.valueType) {
        //单一类型
        if (mapNotEmpty(resultBean.getMultiResult)) {
          String prefix = await getIosPath();
          resultBean.getMultiResult.map((String key, String value) {
            return MapEntry(key, prefix + value);
          });
        }
      } else if (CacheOptionType.multiGetWithMultiType == option.type) {
        //多类型
        if (mapNotEmpty(option.keyTypeMap) &&
            mapNotEmpty(resultBean.getMultiResult)) {
          String prefix = await getIosPath();
          resultBean.getMultiResult.map((String key, String value) {
            if (CacheValueType.file == option.keyTypeMap[key]) {
              return MapEntry(key, prefix + value);
            }
            return MapEntry(key, value);
          });
        }
      }
    }*/
    handleResult(resultBean);
  }

  ///获取IOS路径
  ///
  /// *根据给定目录类型，获取给定相对路径的绝对路径
  /// *参数-参考[IosPathTypeBean]
  Future<String> getIosPath(
      {IosPathTypeBean type,
      HandleResult<HandleCacheResultBean> handleResult}) async {
    if (!Platform.isIOS) {
      return Future.value("");
    }
    type ??= IosPathTypeBean.documents();
    if (type.pathType == "tmp" && stringNotEmpty(IosPath.iosTmpPath)) {
      return Future.value(IosPath.iosTmpPath);
    } else if (type.pathType == "libraryCache" &&
        stringNotEmpty(IosPath.iosLibraryCachePath)) {
      return Future.value(IosPath.iosLibraryCachePath);
    } else if (type.pathType == "library" &&
        stringNotEmpty(IosPath.iosLibraryPath)) {
      return Future.value(IosPath.iosLibraryPath);
    } else if (type.pathType == "documents" &&
        stringNotEmpty(IosPath.iosDocumentsPath)) {
      return Future.value(IosPath.iosDocumentsPath);
    }
    String result = await _channel.invokeMethod<String>(
        'DKFlutterHandleLocalPath', type.pathType);
    if (type.pathType == "tmp") {
      IosPath.iosTmpPath = result;
    } else if (type.pathType == "libraryCache") {
      IosPath.iosLibraryCachePath = result;
    } else if (type.pathType == "library") {
      IosPath.iosLibraryPath = result;
    } else if (type.pathType == "documents") {
      IosPath.iosDocumentsPath = result;
    }
    return Future.value(result);
  }
  ///iOS调取打电话状态监听
  Future<bool> getIOSCallPhoneStatus() async {
    if (!Platform.isIOS) {
      return Future.value(true);
    }
    return await _channel.invokeMethod<bool>('DKFlutterHandleCallPhoneStatus');
  }

  ///获取Native的UserInfo
  Future<UserInfoBean> getUserInfo() async {
    UserInfoBean userInfoBean = UserInfoBean.fromJson(json.decode(
        await _channel.invokeMethod<String>('DKFlutterHandleUserInfo')));
    return userInfoBean;
  }
}

class IosPath {
  static String iosTmpPath;
  static String iosLibraryCachePath;
  static String iosLibraryPath;
  static String iosDocumentsPath;
}
